package com.zekdot.fileclient.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zekdot.fileclient.dto.Envelope;
import com.zekdot.fileclient.service.FileService;
import com.zekdot.fileclient.util.Base64Util;
import com.zekdot.fileclient.util.ConfigInfo;
import com.zekdot.fileclient.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by zekdot on 20-3-29.
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private ConfigInfo configInfo;

    private static List<String> picFormat = new ArrayList<>();
    static {
        picFormat.add(".jpg");
        picFormat.add(".jpeg");
        picFormat.add(".bmp");
        picFormat.add(".png");
        picFormat.add(".gif");
    }

    private Envelope saveFile(MultipartFile file, String path, String userId,int maxSize) {
        if(file.isEmpty()){
            return new Envelope(1,"文件为空",null);
        }
        String type = FileUtil.getSuffix(file.getOriginalFilename());
        if(type == null){
            type = "";
        }
        if(!FileUtil.checkFileSize(file.getSize(),maxSize,"M")){
            return new Envelope(2,"上传了过大的文件",null);
        }
        String filename = FileUtil.getRandomFilename(userId) + type;
        FileUtil.saveFile(file,filename,path);
        String hostId = configInfo.hostId;
        Map<String,String> map = new HashMap<>();
        map.put("filename",filename);
        map.put("hostId",hostId);
        return new Envelope(map);
    }


    @Override
    public Envelope saveFile(MultipartFile file, String userId, int maxSize) {
        String path = configInfo.filePath;
        return saveFile(file,path,userId,maxSize);
    }

    @Override
    public Envelope savePic(MultipartFile file, String userId,int maxSize) {
        String type = FileUtil.getSuffix(file.getOriginalFilename());
        if(type == null){
            return new Envelope(3,"请注明图片格式",null);
        }
        if(!picFormat.contains(type.toLowerCase())){
            return new Envelope(4,"请上传图片文件",null);
        }
        String path = configInfo.picPath;
        return saveFile(file,path,userId,maxSize);
    }

    @Override
    public Envelope savePic(String picCode, String userId, int maxSize) {
        MultipartFile file = Base64Util.base64MutipartFile(picCode);
//        System.out.println(file.getOriginalFilename());
        return savePic(file,userId,maxSize);
    }
}
